package chess.view;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

import chess.model.Session;
import chess.server.NewLineEvent;
import chess.server.NewLineListener;
import chess.server.ServerConnection;

public class Konzole extends ViewPart {
	
	public static final String ID = "chess.view.konzole";

	private StyledText output;

	private Text entry;

	ServerConnection con;

	public Konzole() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void createPartControl(Composite parent) {
		GridLayout layout = new GridLayout();
		layout.marginWidth = 0;
		layout.marginHeight = 0;
		parent.setLayout(layout);

		output = new StyledText(parent, SWT.READ_ONLY | SWT.MULTI | SWT.V_SCROLL
				| SWT.WRAP);
		output.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true,
				true));
		output.setEditable(false);
		
		Font font = new Font(output.getDisplay(), "Courier New", 8, SWT.NORMAL);
		output.setFont(font);
		
		output.setBackground(output.getDisplay().getSystemColor(
				SWT.COLOR_INFO_BACKGROUND));
		output.setForeground(output.getDisplay().getSystemColor(
				SWT.COLOR_INFO_FOREGROUND));

		entry = new Text(parent, SWT.BORDER | SWT.WRAP);
		GridData gridData = new GridData(GridData.FILL, GridData.FILL, true,
				false);
		gridData.heightHint = entry.getLineHeight() * 2;
		entry.setLayoutData(gridData);
		entry.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent event) {
				if (event.character == SWT.CR) {
					sendMessage();
					event.doit = false;
				}
			}
		});

		Session session = Session.getInstance();
		con = session.getConnection();
		con.addNewLineListener(new NewLineListener() {
			@Override
			public void handleNewLineEvent(NewLineEvent e) {
				processMessage(e.getLine());
			}
		});
	}

	private void processMessage(final String message) {
		if (output.isDisposed())
			return;
		output.getDisplay().asyncExec(new Runnable() {
			public void run() {
				if (output.isDisposed())
					return;
				output.append(message);
				output.append("\n");
				scrollToEnd();
			}
		});
	}

	public void sendMessage() {
		String body = entry.getText();
		if (body.length() == 0)
			return;
		con.sendMessage(body);
		output.append("ME:" + body);
		output.append("\n");
		scrollToEnd();
		entry.setText("");
	}

	private void scrollToEnd() {
		int n = output.getCharCount();
		output.setSelection(n, n);
		output.showSelection();
	}

	@Override
	public void setFocus() {
		entry.setFocus();
	}
}
